﻿using System.Windows;
using System;
using System.Windows.Documents;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using Fluent;
using MockupDesigner.AppItems;
using MockupDesigner.AppItems.Documents;
using System.Windows.Input;
using MockupDesigner.AppItems.Commands;

namespace MockupDesigner
{
    public partial class Window1 : RibbonWindow
    {
        public Window1()
        {
            try
            {
                InitializeComponent();

                SetCommandBindings();

                DocumentsTC.ItemsSource = new List<Document>();
                AddNewDocument();
                this.Closing += new System.ComponentModel.CancelEventHandler(Window1_Closing);

                LoadToolboxes();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.MiddleButton == MouseButtonState.Pressed)
            {
                commandProcessor.ExecuteCommand(new CloseDocumentCommand(), this,
                ((System.Windows.Controls.Button)((StackPanel)sender).Children[1]).CommandParameter);
            }
        }

        private void DocumentsTC_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DocumentsTC.Items.Count == 0)
                return;

            if (DocumentsTC.SelectedItem == null)
                DocumentsTC.SelectedIndex = DocumentsTC.Items.Count - 1;

            DesignerCanvas currentDesigner = ((Document)DocumentsTC.SelectedItem).DesignerCanvas;
            currentDesigner.PropertyGrid = this.propertyGrid;
            currentDesigner.MetadataControl = this.metadataControl;
            DesignerItem contextItem = currentDesigner.DataContext as DesignerItem;
            if (contextItem != null && contextItem.IsSelected)
                contextItem.ReloadPropertyGrid();
            else
            {
                this.propertyGrid.SelectedObject = null;
                this.metadataControl.SetMetadatable(null);
            }
        }

        void expander_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            if (MouseButtonState.Pressed == e.RightButton)
                ((Expander)sender).ContextMenu = (System.Windows.Controls.ContextMenu)FindResource("ToolboxContextMenu");
        }

        void expander_Expanded(object sender, RoutedEventArgs e)
        {
            Expander expander = (Expander)sender;
            ((CustomToolbox)expander.Content).IsExpanded = expander.IsExpanded;
        }
    }
}

